﻿function pnpoly(polygon, point) {
  var i, j;
  var c = false;
  for (i = 0, j = polygon.getVertexCount() - 1; i < polygon.getVertexCount(); j = i++)
    if ((((polygon.getVertex(i).lat() <= point.lat()) && (point.lat() < polygon.getVertex(j).lat())) ||
      ((polygon.getVertex(j).lat() <= point.lat()) && (point.lat() < polygon.getVertex(i).lat()))) &&
      (point.lng() < (polygon.getVertex(j).lng() - polygon.getVertex(i).lng()) * (point.lat() - polygon.getVertex(i).lat()) / (polygon.getVertex(j).lat() - polygon.getVertex(i).lat()) + polygon.getVertex(i).lng()))
          c = !c;
  return c;
}
 
function CreateMapPolygon(map, p) {
  var north = p.NorthEast.t;
  var south = p.SouthWest.t;
  var east = p.NorthEast.g;
  var west = p.SouthWest.g;
  
  var poly = GPolygon.fromEncoded(p);
  poly.bounds = new GLatLngBounds(new GLatLng(south, west), new GLatLng(north, east));
  // PolygonDynamicBehavior.None
  if (p.DynamicBehavior != 'None') {
    switch(p.BubbleType) {
      case 'None':
        // None = 0
        poly.Description = null;
        break;
      case 'Name':
        // Name = 1
        poly.Description = p.Name;
        break;
      case 'Description':
        // Description = 2    
        poly.Description = p.Description;
        break;
    }
    poly.HyperLink = p.HyperLink;
    poly.DynamicBehavior = p.DynamicBehavior;
    
    GEvent.addListener(poly, "click", function(point) { 
      switch(poly.DynamicBehavior) {
        case 'ShowBubbleOnClick': // PolygonDynamicBehavior.ShowBubbleOnClick
          map.openInfoWindow(point, poly.Description);
          break;
        case 'RedirectOnClick': // PolygonDynamicBehavior.RedirectOnClick
          window.open(poly.HyperLink);
           break;
      } 
    });
  }
  map.addOverlay(poly);
}

function CreateCachedMapPolygon(map, url, p) {
  GDownloadUrl(url, function(sPoly, statuscode) {
    var poly;
    eval('poly='+sPoly);
    p.polylines = poly.Polygon.Polylines;
    for(var i = 0; i < p.polylines.length; i++) {
      p.polylines[i].color=p.StrokeColor;
      p.polylines[i].weight=p.StrokeWeight;
      p.polylines[i].zoomFactor=p.ZoomFactor;
      p.polylines[i].numLevels=p.NumLevels;
    }
    p.NorthEast = poly.Polygon.NorthEast;
    p.SouthWest = poly.Polygon.SouthWest;
    CreateMapPolygon(map, p);
  });
}
